/*
 * Copyright (C) 2020 Agrui
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "gtest/gtest.h"
#include "MessageHandler.h"
#include <thread>

#include "IpcServer.h"
#include "IpcChannelManager.h"
#include "IpcType.h"
#include "IpcClientManager.h"
#include "IpcApi.h"
#include "SocketClientChannel.h"
#include "IpcService.h"

#define EVENT_TEST_MSG   1
static void testHandlerMessage(Message* msg) {
    switch(msg->what) {
        case EVENT_TEST_MSG: {
            Handler* handler = (Handler*)msg->userObj;
            quit(handler->mQueue);
            break;
        }
        default:
            ASSERT_TRUE(FALSE);
            break;
    }
}

static void simServiceResultCallback(IPC_API_RESULT_T result, void* data, int dataLen, void* userData) {
    printf("simServiceResultCallback \n");
    EXPECT_EQ(result, IPC_API_RESULT_OK);
    if (data && dataLen >= sizeof(int)) {
        EXPECT_EQ(*((int*)data), SIM_STATE_READY);
    }
}

TEST(IpcClientsTest, channelTest) {
    // 初始化IPC系统
    ipcInit();
    
    IpcChannelManager* manager = getDefaultIpcChannelManager();
    ASSERT_NE(manager, nullptr);
    
    // 创建通道，但不依赖实际连接
    IpcChannel* channel0 = newSocketClientChannel(0);
    IpcChannel* channel1 = newSocketClientChannel(1);
    ASSERT_NE(channel0, nullptr);
    ASSERT_NE(channel1, nullptr);
    printf("IpcClientsTest enter \n");
    addChannel(manager, channel0);
    addChannel(manager, channel1);

    // 准备消息循环
    prepare(TRUE);
    Handler* handler = newHandler(testHandlerMessage);
    ASSERT_NE(handler, nullptr);

    // 初始化IPC服务
    IPC_HANDLER ipcHandler = ipcServiceInit(1, IPC_SERVICE_SIM);
    if (ipcHandler != nullptr) {
        ipcBindClient(ipcHandler);
        ipcGetSimState(ipcHandler, this, simServiceResultCallback);
        // 由于连接可能失败，我们只测试基本的消息处理
        std::thread thread = std::thread([handler]() {
            printf("launch a thread \n");
            std::this_thread::sleep_for(std::chrono::milliseconds(100));
            Message* msg = handlerObtainMessage(handler, EVENT_TEST_MSG, nullptr);
            if (msg != nullptr) {
                msg->userObj = handler;
                messageSendToTarget(msg);
            }
        });
        
        loop();
        thread.join();
    }
    
    // 清理资源
    if (handler != nullptr) {
        deleteHandler(handler);
    }
    ipcDeinit();
}



